#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]

use std::env;
use std::fs;
use std::path::Path;
use std::process::Command;

// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn check_folder_exists(folder: &str) -> String {
    println!("folder: {}", folder);
    let path = Path::new(folder);
    if path.exists() && path.is_dir() {
        return '1'.to_string();
    }
    return '0'.to_string();
}

#[tauri::command]
fn open_directory(path: &str) {
    let output = match std::env::consts::OS {
        "windows" => Command::new("cmd")
            .args(&["/C", &format!("start {}", path)])
            .output()
            .expect("Failed to start"),
        "linux" | "macos" => Command::new("open")
            .arg(path)
            .output()
            .expect("Failed to start"),
        _ => panic!("Unsupported OS"),
    };

    if output.status.success() {
        println!("Directory opened successfully.");
    } else {
        println!("Failed to open directory.");
    }
}

#[tauri::command]
fn del_directory(path: &str) -> String {
    let dir_path = Path::new(path);
    if dir_path.exists() && dir_path.is_dir() {
        fs::remove_dir_all(dir_path).expect("无法删除目录");
        println!("目录已删除");
        return '1'.to_string();
    } else {
        println!("目录不存在");
        return '0'.to_string();
    }
}

fn main() {
    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            greet,
            check_folder_exists,
            open_directory,
            del_directory
        ])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
